'use strict';
const db = uniCloud.database()
const foodRecord = db.collection('calorie_intake')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const res = await foodRecord.where({
		openid: event.openid,
		date: event.date
	}).get()
	let data;
	if (res.affectedDocs > 0) {
		const dbCmd = db.command
		if (res.data[0].breakfast && event.breakfast) {
			data = await foodRecord.doc(res.data[0]._id).update({
				breakfast: dbCmd.push(event.breakfast)
			})
		} else if (res.data[0].lunch && event.lunch) {
			data = await foodRecord.doc(res.data[0]._id).update({
				lunch: dbCmd.push(event.lunch)
			})
		} else if (res.data[0].dinner && event.dinner) {
			data = await foodRecord.doc(res.data[0]._id).update({
				dinner: dbCmd.push(event.dinner)
			})
		}
	} else {
		data = await foodRecord.add(event)
	}
	const msg = data.updated ? '修改成功' : '新增成功'
	//返回数据给客户端
	return {
		code: 200,
		msg: msg
	}
};